package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.DamageListGoodsDao;
import com.atguigu.jxc.dao.PurchaseDao;
import com.atguigu.jxc.entity.DamageList;
import com.atguigu.jxc.entity.DamageListGoods;
import com.atguigu.jxc.entity.Goods;
import com.atguigu.jxc.service.DamageListGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author zhmwi
 * @Date 2021/9/5
 * @Dersciption
 */
@Service
public class DamageListGoodsServiceImpl implements DamageListGoodsService {
    
    @Autowired
    private DamageListGoodsDao damageListGoodsDao;
    @Autowired
    private PurchaseDao purchaseDao;
    
    //保存报损单 两张表 报损单表 报损单商品列表
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean save(DamageList damageList, List<DamageListGoods> damageListGoods) {
        //新增报损单表
        if (damageList != null){
            damageListGoodsDao.saveDamageList(damageList);
        }

        //新增报损商品列表
        //所有商品列表(goodsId,goodsCode,goodsName,goodsModel,goodsUnit)
        //单价和数量是前端传的
        List<Goods> goodsList = purchaseDao.selectGoodsAll();
        //根据goodsCode分组
        Map<String, List<Goods>> goodsListMap = goodsList.stream().collect(Collectors.groupingBy(Goods::getGoodsCode));
        System.err.println("damageListGoods"+damageListGoods);
        for (DamageListGoods damageGoods : damageListGoods) {
            String goodsCode = damageGoods.getGoodsCode();
            if (goodsListMap.containsKey(goodsCode)){
                damageGoods.setGoodsId(goodsListMap.get(goodsCode).get(0).getGoodsId());
                damageGoods.setTotal(damageGoods.getGoodsNum() * damageGoods.getPrice());
                damageGoods.setDamageListId(damageList.getDamageListId());
                damageListGoodsDao.saveDamageListGoods(damageGoods);
            }
        }

        return true;
    }

    //查询报损单
    @Override
    public List<DamageList> list(String sTime, String eTime) {
        return damageListGoodsDao.list(sTime,eTime);

    }

    //查询商品报损单信息
    @Override
    public List<DamageListGoods> getGoodsList(Integer damageListId) {
        return damageListGoodsDao.getGoodsList(damageListId);
    }
}
